import 'dart:io';

import 'dart:io';
import '_base_export.dart';

import 'app_util.dart';
//import 'package:imei_plugin/imei_plugin.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:device_info/device_info.dart';

class AppSession {
  static late String udid;
  static String? pushid;
  static late Map platformConst;
  static late PackageInfo packageInfo;
  static late SharedPreferences prefs;
  static AppUtil appUtil = new AppUtil();
  static AppRequest appReq = new AppRequest();

  static String? stripePayMethodId;
  static bool wxIns = false;
  static String? authortoken;
  static Map creditcard = {};
  static bool popupFlag = false;
  static Map msgPage = {};

  static Map<String, dynamic> addrEdit = {};

  static Map<String, dynamic> userAddr = {
    "addr": "",
    "lat": 0.0,
    "lng": 0.0,
    "unit": "",
    "postal": "",
    "buzz": "",
    "consignee_name": "",
    "consignee_phone": ""
  };

  static int bottomIndex = 0;

  static Offset? homeCart;
  static late GlobalKey homeRoot;
  static Offset? prodListCart;
  static late GlobalKey prodListRoot;

  static Map currentLocation = {"lat": 0.0, "lng": 0.0};
  static int wh_id = 0;
  static int wholesale_wh_id = 0;

  static init() async {
    if (Platform.isIOS) {
      platformConst = AppConfig.constsIos;
    } else {
      platformConst = AppConfig.constsAndroid;
    }
    prefs = await SharedPreferences.getInstance();

    await getImei();
    await getPackageInfo();
    //currentLocation = {"lat": 0.0, "lng": 0.0};
    await getWhid();
    popupFlag = false;

    // appUtil = new AppUtil();
    await appUtil.initLoad();
  }

  static getImei() async {
    udid = await _getId();
  }

  static Future<String> _getId() async {
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    if (Platform.isIOS) {
      IosDeviceInfo iosDeviceInfo = await deviceInfo.iosInfo;
      return iosDeviceInfo.identifierForVendor; // unique ID on iOS
    }else{
      AndroidDeviceInfo androidDeviceInfo = await deviceInfo.androidInfo;
      return androidDeviceInfo.androidId; // unique ID on Android
    }
  }

  static getPackageInfo() async {
    packageInfo = await PackageInfo.fromPlatform();
  }

  static getWhid() async {
    var lv_whid_str = prefs.getString('wh_id');

    try {
      if (lv_whid_str != null) wh_id = int.parse(lv_whid_str);
    } catch (e) {
      print(e);
    }
  }

  static setWhid(int iv_wh_id) async {
    prefs.setString('wh_id', iv_wh_id.toString());
    wh_id = iv_wh_id;
  }

  static setWeChatIns(bool iv_wechat) {
    wxIns = iv_wechat;
  }

  static setMsgPage({
    String? iv_date,
    String? iv_subject,
    String? iv_content,
  }) async {
    msgPage['date'] = iv_date;
    msgPage['subject'] = iv_subject;
    msgPage['content'] = iv_content;
  }

  static refreshToken() async {
    try {
      var _local_refresh = prefs.getString('token_refreshed');
      var _local_fbtoken = prefs.getString('fb_token');
      int _token_updated =
          ((_local_refresh ?? '').isNotEmpty) ? int.parse(_local_refresh!) : 0;
      int _current_time = DateTime.now().millisecondsSinceEpoch ~/ 1000;
      print(_local_refresh);
      print(_local_fbtoken);
      print(_token_updated);
      print(_current_time);
      print(_current_time - _token_updated);

      if (((authortoken ?? '').isEmpty) ||
          (_current_time - _token_updated > 2400) ||
          ((_local_fbtoken ?? '').isEmpty)) {
        print('test');
        final FirebaseAuth _auth = FirebaseAuth.instance;
        var _auser = _auth.currentUser;
        print('test1');
        print(_auser);
        if (_auser != null) {
          authortoken = await _auser.getIdToken(true);
          // IdTokenResult _fb_result = await _auser.getIdToken(refresh: true);
          if (authortoken != null) {
            // authortoken = _fb_result.token;
            prefs.setString('token_refreshed', _current_time.toString());
            prefs.setString('fb_token', authortoken.toString());
          } else
            authortoken = '';
        } else {
          authortoken = '';
        }
      } else {
        authortoken = _local_fbtoken;
      }
    } catch (error) {
      authortoken = '';
      // Print to console/logcat
      print('Error: $error');
    }
    return authortoken;
  }

  // static setRegion(int iv_region) async {
  //   print(iv_region);
  //   region = iv_region;
  //   if ((AppUtil.region_list ?? {}).isNotEmpty)
  //     region_text = AppUtil.region_list[iv_region.toString()];
  //   prefs.setString('g_region', iv_region.toString());
  //   prefs.setString('g_region_text', AppUtil.region_list[iv_region.toString()]);
  // }

  // static setPhoneVerify() async {
  //   phoneVerified = true;
  //   prefs.setString('g_phone_verified', 'X');
  // }

  static clearSession() async {
    authortoken = '';
    creditcard = {};
    userAddr = {};
    popupFlag = false;
    prefs.setString('fb_token', '');
    prefs.setString('wh_id', '');
    prefs.setString('token_refreshed', 0.toString());
  }
}
